package brian.android.mvc.event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import android.app.Activity;
import android.view.View;
import brian.android.mvc.bean.BeanFactory;

public abstract class AbstactEventHandler implements EventHandler {
	private Activity activity;
	private Method eventMethod;
	
	@Override
	public void setEvent(View view, Activity activity, Method eventMethod) {
		this.activity = activity;
		this.eventMethod = eventMethod;
		
		Method setMethod = getMethod(view);
		try {
			setMethod.invoke(view, this);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	private Method getMethod(View view) {
		try {
			return view.getClass().getMethod(getSetMethodName(view), getEventListener());
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	protected List<Object> getArguments(Method eventMethod, Object eventView, Class clazz) {
		return BeanFactory.getArguments(eventMethod, getActivity(), eventView, clazz);
	}
	
	@SuppressWarnings("unchecked")
	protected List<Object> getArguments(Method eventMethod, Object[] arguments, Class[] argumentTypes) {
		return BeanFactory.getArguments(eventMethod, getActivity(), arguments, argumentTypes);
	}

	private String getSetMethodName(View view) {
		return "set" + getEventListener().getSimpleName();
	}
	
	public Activity getActivity() {
		return activity;
	}

	public Method getEventMethod() {
		return eventMethod;
	}
	@SuppressWarnings("unchecked")
	protected abstract Class getEventListener();
}
